package cn.net.xyan.blossom.webUI.ui


import cn.net.xyan.blossom.kotlin.base64
import com.github.vok.karibudsl.*
import com.vaadin.shared.ui.MarginInfo
import com.vaadin.ui.*
import java.io.ByteArrayOutputStream
import java.io.OutputStream

fun (@VaadinDsl HasComponents).textAreaWithUpload(caption: String? = null, value: String? = null, block: (@VaadinDsl TextAreaWithUpload).() -> Unit = {}): TextAreaWithUpload {
    val field = TextAreaWithUpload(caption)
    if (value != null) field.value = value
    init(field, block)
    return field
}

class TextAreaWithUpload(caption: String? = null) : CustomField<String?>(), Upload.Receiver, Upload.SucceededListener {

    lateinit var textArea: TextArea

    lateinit var title:Label

    var output: ByteArrayOutputStream? = null
    var filename: String? = null
    var mimeType: String? = null

    init {
        this.caption = caption
    }

    override fun receiveUpload(filename: String?, mimeType: String?): OutputStream {
        this.filename = filename
        this.mimeType = mimeType

        output = ByteArrayOutputStream()

        return output!!
    }

    override fun uploadSucceeded(event: Upload.SucceededEvent?) {
        val base64 = output?.toByteArray()?.base64()
        this.value = base64

        title.value = "已上传:$filename"
        title.isVisible = true
    }

    override fun initContent(): Component {
        val root = VerticalLayout()
        val self = this
        root.apply {
            margin = MarginInfo(false, false, false, false)
            horizontalLayout {
                upload {
                    buttonCaption = "上传"

                    receiver = self
                    addSucceededListener(self)
                }
                title = label(null){
                    alignment = Alignment.BOTTOM_LEFT
                    isVisible = false
                }
            }
            textArea = textArea {
                setSizeFull()
                expandRatio = 1.0f
            }
        }

        return root
    }

    override fun getValue(): String? {
        return textArea.value
    }

    override fun doSetValue(value: String?) {
        textArea.value = value?:""
        title.isVisible = false
    }


}